package com.duolaibei.business.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.model.ShopListData;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.activity.MyCaptureActivity;
import com.duolaibei.business.view.dialog.ShopDialog;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by xlm on 2017/11/6 0006
 */

public class SearchOrderActivity extends BaseActivity {

    @Inject(R.id.begin_search)
    private TextView mTextViewSearch;
    @Inject(R.id.order_nopay)
    private TextView mTextViewNopay;
    @Inject(R.id.order_payed)
    private TextView mTextViewPayed;
    @Inject(R.id.order_drawback)
    private TextView mTextViewDrawBack;
    @Inject(R.id.order_begin)
    private TextView mTextViewBegin;
    @Inject(R.id.order_end)
    private TextView mTextViewEnd;
    @Inject(R.id.shop_list_recycle)
    private RecyclerView mRecyclerView;
    private CommonAdapter<ShopListData.DataBeanX.DataBean> mCommonAdapter;
    private List<ShopListData.DataBeanX.DataBean> mBeanList;
    @Inject(R.id.choose_shop)
    private TextView mTextViewCoose;
    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mTextViewTitle;
    @Inject(R.id.ishow_shop)
    private LinearLayout mLayoutShop;
    @Inject(R.id.trade_id)
    private EditText mEditTextTradeId;
    @Inject(R.id.trade_search)
    private TextView mTextViewScan;
    private String shopId;//门店id
    private String begintime;//开始时间
    private String endtime;//结束时间
    private String state;//支付状态
    private String tradeNum;//订单号

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_search_order);
    }

    @Override
    protected void initViews() {
        mTextViewTitle.setText("查单");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
//        getShopList();
//        setShopAdapter();
        if (!"merchant".equals(String.valueOf(PreferenceUtil
                .getParam(Preferences.LOGINTYPE, "")))) {
            mLayoutShop.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onSetListener() {
        mTextViewSearch.setOnClickListener(this);
        mTextViewNopay.setOnClickListener(this);
        mTextViewPayed.setOnClickListener(this);
        mTextViewDrawBack.setOnClickListener(this);
        mTextViewEnd.setOnClickListener(this);
        mTextViewBegin.setOnClickListener(this);
        mTextViewCoose.setOnClickListener(this);
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTextViewScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission();
            }
        });
    }

    private static final int PERMISSON_CAMERA = 0;

    private void checkPermission() {
        if (checkCameraPermission(PERMISSON_CAMERA)) {
            permissionOk();
        }
    }

    private final int REQUEST_CODE = 0;

    /**
     * 所有权限都已经获取
     */
    private void permissionOk() {
        Intent intent = new Intent(getThis(), MyCaptureActivity.class);
        intent.putExtra("title", "扫码查单");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToast("拒绝此权限，您将无法使用摄像头权限");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                Bundle bundle = data.getExtras();
                if (CodeUtils.RESULT_SUCCESS == bundle.getInt(CodeUtils.RESULT_TYPE)) {
                    tradeNum = bundle.getString(CodeUtils.RESULT_STRING);
                    Intent intent = new Intent();
                    if (!CommonUtil.isEmpty(tradeNum)) {
                        intent.putExtra("tradeNum", tradeNum);//订单ID
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.choose_shop) {
            showShopDialog();
        } else if (R.id.order_begin == v.getId()) {
            showTimePicker(mTextViewBegin, null, "开始时间");

        } else if (R.id.order_end == v.getId()) {
            showTimePicker(null, mTextViewEnd, "结束时间");
        } else if (R.id.order_nopay == v.getId()) {
            mTextViewNopay.setSelected(true);
            mTextViewPayed.setSelected(false);
            mTextViewDrawBack.setSelected(false);
            state = "0";//未支付
        } else if (R.id.order_payed == v.getId()) {
            mTextViewNopay.setSelected(false);
            mTextViewPayed.setSelected(true);
            mTextViewDrawBack.setSelected(false);
            state = "1";//已收款
        } else if (R.id.order_drawback == v.getId()) {
            mTextViewNopay.setSelected(false);
            mTextViewPayed.setSelected(false);
            mTextViewDrawBack.setSelected(true);
            state = "-1";//已退款
        } else if (R.id.begin_search == v.getId()) {
            String begin = mTextViewBegin.getText().toString();
            tradeNum = mEditTextTradeId.getText().toString();
            if (!"开始时间".equals(begin)) {
                begintime = String.valueOf(CommonUtil.formatDate(begin, "yyyy-MM-dd HH:mm:ss"));
            }
            String end = mTextViewEnd.getText().toString();
            if (!"结束时间".equals(end)) {
                endtime = String.valueOf(CommonUtil.formatDate(end, "yyyy-MM-dd HH:mm:ss"));
            }

            Intent intent = new Intent();
            if (!CommonUtil.isEmpty(shopId)) {
                intent.putExtra("shopId", shopId);//门店ID
            }
            if (!CommonUtil.isEmpty(tradeNum)) {
                intent.putExtra("tradeNum", tradeNum);//订单ID
            }

            if (!CommonUtil.isEmpty(begintime)) {
                intent.putExtra("begintime", begintime.substring(0, begintime.length() - 3));//开始时间
                if (CommonUtil.isEmpty(endtime)) {
                    showToast("请选择结束时间");
                    return;
                }
            }
            if (!CommonUtil.isEmpty(endtime)) {
                intent.putExtra("endtime", endtime.substring(0, endtime.length() - 3));//结束时间
                if (CommonUtil.isEmpty(begintime)) {
                    showToast("请选择开始时间");
                    return;
                }
            }
            if (!CommonUtil.isEmpty(state)) {
                intent.putExtra("state", state);//支付状态
            }
            if (CommonUtil.isEmpty(shopId)
                    && CommonUtil.isEmpty(begintime)
                    && CommonUtil.isEmpty(endtime)
                    && CommonUtil.isEmpty(state)
                    && CommonUtil.isEmpty(tradeNum)
                    ) {
                showToast("请选择搜索条件");
                return;
            }
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private ShopDialog mShopDialog;

    /**
     * 选择门店信息
     */
    private void showShopDialog() {
        if (mShopDialog == null) {
            mShopDialog = new ShopDialog(getThis());
        }
        mShopDialog.setCancelable(true);
        mShopDialog.setShopDialogListener(new ShopDialog.ShopDialogListener() {
            @Override
            public void onItemSelected(String name, String id) {
                super.onItemSelected(name, id);
                mTextViewCoose.setText(name);
                shopId = id;
            }
        });
        mShopDialog.show();
    }

    /**
     * 初始化数据 设置第一个为选中状态
     */
    private void initBeanList() {
        for (int i = 0; i < mBeanList.size(); i++) {
            if (i == 0) {
                mBeanList.get(i).setSelected(true);
            } else {
                mBeanList.get(i).setSelected(false);
            }
        }
    }

    /**
     * 点击改变数据
     */
    private void setBeanList(ShopListData.DataBeanX.DataBean dataBean) {
        for (int i = 0; i < mBeanList.size(); i++) {
            if (dataBean.getId().equals(mBeanList.get(i).getId())) {
                mBeanList.get(i).setSelected(true);
            } else {
                mBeanList.get(i).setSelected(false);
            }
        }
        mCommonAdapter.notifyDataSetChanged();
    }

    /**
     * 更新显示数据
     */
    private void notifyDataRefresh() {
        initBeanList();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 设置adapter
     */
    private void setShopAdapter() {
        mBeanList = new ArrayList<>();
        mCommonAdapter = new CommonAdapter<ShopListData.DataBeanX.DataBean>(getThis(), R.layout.item_order_list, mBeanList) {
            @Override
            protected void convert(ViewHolder holder, final ShopListData.DataBeanX.DataBean dataBean, int position) {
                holder.setText(R.id.item_order_text, String.valueOf(mBeanList.get(position).getName()));
                holder.getView(R.id.item_order_text).setSelected(dataBean.isSelected());
                RelativeLayout mLayout = (RelativeLayout) holder.getView(R.id.item_root_order);
                if (position % 3 == 0) {
                    mLayout.setGravity(Gravity.LEFT);
                } else if (position % 3 == 1) {
                    mLayout.setGravity(Gravity.CENTER);
                } else if (position % 3 == 2) {
                    mLayout.setGravity(Gravity.RIGHT);
                }
                //点击选择门店
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setBeanList(dataBean);
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new GridLayoutManager(getThis(), 3));
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    /**
     * 获取全部门店列表
     */
    private void getShopList() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.SHOPLIST);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
//        param.add("uid", "315");
        param.add("login_type", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, "")));
        param.add("current_page", "1");//在一页返回全部门店
        param.add("page_size", "500");//每页显示500条数据
        param.add("sign", param.getMd5String());
        showLoading("加载中");
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
                        ShopListData data = GsonUtil.GsonToBean(string, ShopListData.class);
                        mBeanList.clear();
                        mBeanList.addAll(data.getData().getData());
                        notifyDataRefresh();
                    } else {
                        showToast(result.getInfo());
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }

    /**
     * 显示时间选择器
     */
    private void showTimePicker(final TextView begin, final TextView end, String title) {
        Calendar calendar = Calendar.getInstance();
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (begin != null) {
                    mTextViewBegin.setText(getTime(date));
                }
                if (end != null) {
                    mTextViewEnd.setText(getTime(date));
                }
            }
        })
                .setType(new boolean[]{true, true, true, true, true, true})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(Color.parseColor("#e46641"))
                .setCancelColor(Color.parseColor("#e46641"))
                .setSubCalSize(14)
                .setContentSize(15)//滚轮文字大小
                .setTitleSize(16)//标题文字大小
                .setTitleText(title)//标题文字
                .setLineSpacingMultiplier(2.2f)
                .isCenterLabel(true)
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setTitleBgColor(Color.parseColor("#ffffff"))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                .setDate(calendar)// 默认是系统时间*/
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

}
